package com.fengmi.controller;

import cn.hutool.json.JSONUtil;
import com.fengmi.utils.Qiniu;
import com.fengmi.vo.InfoResult;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
/**
 * Author: 施俊豪
 * Date: 2022/1/18 9:06
 * Note: 七牛云图片上传
 */
@Api(description="七牛云图片上传")
@RequestMapping("upload")
@CrossOrigin
@RestController
public class UploadController {

    @Autowired
    private Qiniu qiniu;

    @ApiOperation(value = "七牛云图片上传方法")
    @PostMapping("/img")
    public InfoResult upload(MultipartFile file) {

        System.out.println("文件名" + file.getOriginalFilename());

        //文件存储？
        //方案一：搭建分布式文件存储系统（阿里开源的fastdfs【分布式的文件存储系统】）
        //方案二：可以使用云厂商提供的oss【对象资源存储】服务（阿里云、腾讯云、华为云、七牛云）

        //构造一个带指定 Region 对象的配置类，指定bucket对应的区
        Configuration cfg = new Configuration(Region.huanan());
        //...其他参数参考类注释

        UploadManager uploadManager = new UploadManager(cfg);
        //..生成文件上传凭证,准备上传
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = null;

        try {
            //获取文件的字节数组
            byte[] bytes = file.getBytes();

            Auth auth = Auth.create(qiniu.getAk(), qiniu.getSk());
            String upToken = auth.uploadToken(qiniu.getBucket());

            Response response = uploadManager.put(bytes, key, upToken);
            //解析上传成功的结果(使用hutool工具包)
            DefaultPutRet defaultPutRet = JSONUtil.toBean(response.bodyString(), DefaultPutRet.class);

            System.out.println("key=====>" + defaultPutRet.key);
            System.out.println("hash=====>" + defaultPutRet.hash);

            //拼接完整的图片地址，存储到数据库中
            String url = qiniu.getHost() + defaultPutRet.hash;
            System.out.println("url======>" + url);
            InfoResult infoResult = new InfoResult();
            infoResult.setSuccess(true);
            infoResult.setMsg("上传成功!!!");
            infoResult.setData(url);
            return infoResult;
        } catch (Exception e) {
            e.printStackTrace();
            InfoResult infoResult = new InfoResult();
            infoResult.setSuccess(false);
            infoResult.setMsg("error!!!");
            infoResult.setData("");
            return infoResult;
        }

    }
}